<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\YjBanner;
use App\Models\YjNews;
use App\Models\YjPdf;
use App\Models\YjUser;
use Illuminate\Http\Request;
use phpDocumentor\Reflection\File;

class ApiController extends Controller
{
    //
    //保存用户信息(手机号)
    public function InsertUserMessage()
    {
        if (request()->isMethod("post")) {

            $data["phone"] = \request("phone");
            $data["created_at"] = date("Y-m-d H:i:s", time());

            if (\request("phone")) {

                if (preg_match("/^1(3|4|5|6|7|8|9)\d{9}$/", $data['phone'])) {

                    $all_message = YjUser::getAllPhone()->toArray();
                    $all_message = array_column($all_message, "phone");

                    if (!in_array(\request("phone"), $all_message)) {

                        $insert = YjUser::saveUserMessage($data);

                        if ($insert) {

                            return toJson(20000, "保存成功");
                        } else {
                            return toJson(20003, "保存失败");
                        }
                    } else {
                        return toJson(20003, "该手机号码已提交");
                    }
                } else {
                    return toJson(20003, "手机号码格式不正确");
                }
            } else {
                return toJson(20003, "手机号码不能为空");
            }
        }
    }

    //获取轮播图图片信息
    public function GetBanners()
    {

        $data = YjBanner::getAllBanners();
        foreach($data as $k =>$v){

            $data[$k]["img"] = config("app.url")."uploads/". $data[$k]["img"] ;
        }

        if (!empty($data)) {

            return toJson(20000, "查询成功", 200, $data);
        } else {

            return toJson(20001, "查询失败");
        }
    }

    //获取所有PDF文件
    public function GetPDF()
    {
          $type = \request("type") ;

        $data = YjPdf::getAllPDF($type);
        foreach($data as $k =>$v){
            $data[$k]["pdf"] =  config("app.url")."uploads/".$data[$k]["pdf"] ;
        }
        if ($data) {

            return toJson(20000, "查询成功", 200, $data);
        } else {

            return toJson(20001, "查询失败");
        }
    }


    public function getAllNews(){

        $data  = YjNews::all();

        if ($data) {

            return toJson(20000, "查询成功", 200, $data);
        } else {

            return toJson(20001, "查询失败");
        }
    }

    public function  PDFSearch(){

        if(request()->isMethod("post")){
            $message = request("message");
            $type = \request("type");

            $data  = YjPdf::getAllPDF($type,$message) ;
            foreach($data as $k =>$v){
                $data[$k]["pdf"] =  config("app.url")."uploads/".$data[$k]["pdf"] ;
            }
            if($data){

                return toJson(20000,"查询成功",200,$data) ;
            }else{
                return  toJson(20001,"查询失败") ;
            }
        }
    }
}
